import { defineStore } from 'pinia';
import { createStorage } from '@/utils/Storage';
import { store } from '@/store';
import { ACCESS_TOKEN, CURRENT_USER, IS_LOCKSCREEN } from '@/store/mutation-types';
import { ResultEnum } from '@/enums/httpEnum';

import { useGlobSetting } from '@/hooks/setting';

const globSetting = useGlobSetting();

//组装完整图片地址
function getImgUrl(url: string): string {
  const { imgUrl } = globSetting;
  return /(^http|https:\/\/)/g.test(url) ? url : `${imgUrl}${url}`;
}

const Storage = createStorage({ storage: localStorage });
import { profileInfo } from '@/api/system/profile';
import api from '@/api/system/auth';
import { storage } from '@/utils/Storage';

export interface IUserState {
  token: string;
  username: string;
  nickname: string;
  avatar: string;
  permissions: any[];
  info: any;
}

export interface PermissionItem {
  id: number;
  name: string;
  value: string;
  orders: number;
  createDate: string;
  updateDate: string;
}

export interface UserInfoItem {
  id: string;
  username: string;
  nickname: string;
  avatar: string;
  mobile: string;
  realName: string;
  email: string;
  deptId: number;
  postId: number;
  roles: any[];
  permissions: any[];
  authorities: string[];
  createDate: string;
  updateDate: string;
}

export const useUserStore = defineStore({
  id: 'app-user',
  state: (): IUserState => ({
    token: Storage.get(ACCESS_TOKEN, ''),
    username: '',
    nickname: '',
    avatar: '',
    permissions: [],
    info: Storage.get(CURRENT_USER, {})
  }),
  getters: {
    getToken(): string {
      return this.token;
    },
    getAvatar(): string {
      return getImgUrl(this.avatar);
    },
    getUsername(): string {
      return this.username;
    },
    getNickname(): string {
      return this.nickname;
    },
    getPermissions(): PermissionItem[] {
      return this.permissions;
    },
    getUserInfo(): UserInfoItem {
      return this.info;
    },
  },
  actions: {
    setToken(token: string) {
      this.token = token;
    },
    setAvatar(avatar: string) {
      this.avatar = avatar;
    },
    setUsername(username: string) {
      this.username = username;
    },
    setNickname(nickname: string) {
      this.nickname = nickname;
    },
    setPermissions(permissions: PermissionItem[]) {
      this.permissions = permissions;
    },
    setUserInfo(info) {
      this.info = info;
    },
    // 登录
    async login(userInfo) {
      try {
        const response = await api.login(userInfo);
        const { data, code } = response;
        if (code === ResultEnum.SUCCESS) {
          const ex = 7 * 24 * 60 * 60 * 1000;
          storage.set(ACCESS_TOKEN, data.token, ex);
          storage.set(CURRENT_USER, data, ex);
          storage.set(IS_LOCKSCREEN, false);
          this.setToken(data.token);
        }
        return Promise.resolve(response);
      } catch (e) {
        return Promise.reject(e);
      }
    },

    // 获取用户信息
    GetInfo() {
      return new Promise((resolve, reject) => {
        profileInfo()
          .then((res) => {
            console.log(res)
            const result = res.user;
            if (result.permissions && result.permissions.length) {
              const permissionsList = result.permissions;
              this.setPermissions(permissionsList);
            }
            this.setAvatar(result.avatar);
            this.setUsername(result.username);
            this.setNickname(result.nickname);
            this.setUserInfo(result);


            console.log(this.getUserInfo.username)
            resolve(result);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 登出
    async logout() {
      api.logout({}).then(() => {
        this.setPermissions([]);
        this.setUserInfo('');
        storage.remove(ACCESS_TOKEN);
        storage.remove(CURRENT_USER);
        return Promise.resolve('');
      });
    },
  },
});

// Need to be used outside the setup
export function useUserStoreWidthOut() {
  return useUserStore(store);
}
